<template>
  <div>
    <el-row>
      <el-col :span="6">
        <div class="box">
          <formPanel ref="formPanel" :list="formList" :cols="1" labelWidth="100" :isSubmitBtn="false" @formChange="formChange"></formPanel>
          <ButtonArea :style="{ paddingLeft: '80px' }">
            <AjaxButton type="primary" :click="save" :disabled="saveFlag">保存</AjaxButton>
            <el-button type="primary" icon="el-icon-printer" :disabled="printButtonAble" @click="printRecord">打印</el-button>
            <AjaxButton type="primary" :click="reset" :disabled="cancelFlag">取消</AjaxButton>
          </ButtonArea>
        </div>
      </el-col>
      <el-col :span="18">
        <div class="box" :style="{ display: 'inline-block', width: '98%' }">
          <el-col :span="18">
            <TopFilter ref="TopFilter" :list="topFilterList" :cols="2" labelWidth="100" :isSubmitBtn="false" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>
          </el-col>
          <!-- <ButtonArea :style="{ paddingLeft: '100px' }"> -->
          <el-col :span="6" :style="{ textAlign: 'right' }">
            <el-button type="primary" @click="query">查询</el-button>
            <!-- <el-button @click="clear" :disabled="clearFlag">重置</el-button> -->
          </el-col>
        </div>
        <!-- </ButtonArea> -->
        <div class="box">
          <el-col :span="3" :style="{ textAlign: 'center', lineHeight: '32px' }">预收款明细</el-col>
          <FilterTable
            ref="table1"
            :fetchapi="fetchapi1"
            :dataSource="dataSource1"
            :isSelectColumn="false"
            :isPagination="true"
            :isColumnFilter="false"
            :isToperInfo="false"
            height="auto"
            :columns="columns1"
            :params="fetchParams"
            :datakey="'rows'"
            :onColumnsChange="columns => (this.columns1 = columns)"
          ></FilterTable>
        </div>
        <div class="box">
          <el-col :span="3" :style="{ textAlign: 'center', lineHeight: '32px' }">保险费明细</el-col>
          <FilterTable
            ref="table2"
            :fetchapi="fetchapi2"
            :dataSource="dataSource2"
            :isSelectColumn="false"
            :isPagination="true"
            height="auto"
            :columns="columns2"
            :params="fetchParams"
            :datakey="'rows'"
            :onColumnsChange="columns => (this.columns2 = columns)"
            :isColumnFilter="false"
            :isToperInfo="false"
          ></FilterTable>
        </div>
        <div class="box">
          <el-col :span="3" :style="{ textAlign: 'center', lineHeight: '32px' }">车辆明细</el-col>
          <FilterTable
            ref="table3"
            :fetchapi="fetchapi3"
            :dataSource="dataSource3"
            :isSelectColumn="false"
            :isPagination="true"
            height="auto"
            :columns="columns3"
            :params="fetchParams"
            :datakey="'rows'"
            :onColumnsChange="columns => (this.columns3 = columns)"
            :isColumnFilter="false"
            :isToperInfo="false"
          ></FilterTable>
        </div>
        <BaseDialog :visible.sync="visible" title="选择客户" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
          <customerModal :type="handleType" :customerCode="formList[1].initialValue" @close="closeHandler" @change="getCustomerInfo" />
        </BaseDialog>
        <div v-if="printVehicledShow">
          <BasePrint ref="printVehicled" :data="this.printList" template="templateRegister" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getUserId, getUser } from '@/assets/js/auth';
import { queryVehicle, queryInsurancePay, queryPrePay, save, findInvoiceType, getAllUser } from '@/api/finance/advancesReceived/register';
import customerModal from './customerModal';
import moment from 'moment';
export default {
  name: 'Registers',
  components: { customerModal },
  mixins: [dictionary],
  data() {
    this.BaseTable1 = null;
    this.BaseTable2 = null;
    this.BaseTable3 = null;
    return {
      printVehicledShow: false,
      topFilterList: this.createTopFilters(),
      formList: this.createForm(),
      fetchParams: { xhrAbort: true },
      fetchapi1: queryPrePay,
      fetchapi2: queryInsurancePay,
      fetchapi3: queryVehicle,
      visible: false,
      dialogTitle: '',
      columns1: this.createTableColumns1(),
      columns2: this.createTableColumns2(),
      columns3: this.createTableColumns3(),
      handleType: '',
      formData: null,
      dataSource1: [],
      dataSource2: [],
      dataSource3: [],
      saveFlag: true,
      printButtonAble: true,
      cancelFlag: true,
      clearFlag: false,
      printList: {}
    };
  },
  computed: {},
  mounted() {
    this.BaseTable1 = this.$refs.table1.$refs.pageTable;
    this.BaseTable2 = this.$refs.table2.$refs.pageTable;
    this.BaseTable3 = this.$refs.table3.$refs.pageTable;
  },
  created() {
    this.getDictList();
  },
  methods: {
    Capitalization(n) {
      if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) {
        return '';
      }
      var unit = '仟佰拾亿仟佰拾万仟佰拾圆角分',
        str = '';
      n += '00';
      var p = n.indexOf('.');
      if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2);
      unit = unit.substr(unit.length - n.length);
      for (var i = 0; i < n.length; i++) str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
      return str
        .replace(/零(仟|佰|拾|角)/g, '零')
        .replace(/(零)+/g, '零')
        .replace(/零(万|亿|圆)/g, '$1')
        .replace(/(亿)万|壹(拾)/g, '$1$2')
        .replace(/^圆零?|零分/g, '')
        .replace(/圆$/g, '圆整');
    },
    createTopFilters() {
      return [
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'customerCode',
          placeholder: '请输入...',
          rules: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.selectCustomer(props)}></el-button>;
          }
        }
      ];
    },
    createForm() {
      return [
        {
          type: 'INPUT',
          label: '收款单号',
          fieldName: 'preReceiveNo',
          // placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '客户编号',
          fieldName: 'customerCode',
          // placeholder: '请输入...',
          rules: [{ required: true, message: '请输入客户编号', trigger: 'blur' }],
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.selectCustomer(props)}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license',
          // placeholder: '请输入...'
          unitRender: props => {
            return <el-button icon="el-icon-search" onClick={() => this.selectCustomer(props)}></el-button>;
          }
        },
        {
          type: 'INPUT',
          label: '客户名称',
          fieldName: 'customerName',
          // placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '收款类别',
          fieldName: 'receiveType',
          placeholder: '请输入...',
          disabled: true,
          initialValue: 80301004,
          itemList: [
            { text: '预收款', value: 80301004 },
            { text: '保险费', value: 80301005 },
            { text: '其他', value: 80301008 }
          ]
        },
        {
          type: 'SELECT',
          label: '付款方式',
          fieldName: 'payTypeCode',
          placeholder: '请选择...',
          disabled: true,
          itemList: this.createDictList('8044')
        },
        {
          type: 'INPUT_NUMBER',
          label: '收款金额',
          precision: 2,
          fieldName: 'receiveAmount',
          placeholder: '请输入...',
          disabled: true,
          rules: [{ required: true, message: '请填写收款金额', trigger: 'blur' }]
        },
        {
          type: 'INPUT',
          label: '支票号码',
          fieldName: 'checkNo',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '发票类型',
          fieldName: 'invoiceTypeCode',
          placeholder: '请选择...',
          itemList: [],
          disabled: true
        },
        {
          type: 'INPUT',
          label: '票据号码',
          fieldName: 'billNo',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '经手人',
          fieldName: 'handler',
          placeholder: '请输入...',
          disabled: true,
          initialValue: getUserId(),
          itemList: [{ text: getUser(), value: getUserId() }]
        },
        {
          type: 'INPUT',
          label: '备注',
          fieldName: 'remark',
          placeholder: '请输入...',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '客户类型',
          fieldName: 'prePayCusType',
          placeholder: '请选择...',
          disabled: true,
          itemList: this.createDictList('8052')
        }
      ];
    },
    createTableColumns1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '预收款单号',
          dataIndex: 'PRE_RECEIVE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发生时间',
          dataIndex: 'HANDLE_TIME',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '经手人',
          dataIndex: 'HANDLER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.RECEIVE_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '本次支出',
          dataIndex: 'PAYOUT_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.PAYOUT_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '本次结余',
          dataIndex: 'AFTER_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.AFTER_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '付款方式',
          dataIndex: 'PAY_TYPE_CODE',
          sorter: true,
          filter: true,
          render: props => {
            return <span>{this.createDictText(props.row.PAY_TYPE_CODE, '8044')}</span>;
          }
        },
        {
          title: '支票号码',
          dataIndex: 'CHECK_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '票据号码',
          dataIndex: 'BILL_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发票类型',
          dataIndex: 'INVOICE_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 200
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          render: props => {
            return (
              <el-tooltip class="item" content={props.row.REMARK} placement="top">
                <span>{props.row.REMARK}</span>
              </el-tooltip>
            );
          }
        }
      ];
    },
    createTableColumns2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '收款单号',
          dataIndex: 'RECEIVE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '收款日期',
          dataIndex: 'RECEIVE_DATE',
          sorter: true,
          filter: true,
          filterType: 'input',
          dateFormat: 'yyyy-MM-dd'
        },
        {
          title: '经手人',
          dataIndex: 'HANDLER',
          sorter: true,
          editable: false,
          editType: 'select',
          editItems: [],
          filterType: 'input'
        },
        {
          title: '收款金额',
          dataIndex: 'RECEIVE_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{props.row.RECEIVE_AMOUNT.toFixed(2)}</span>;
          }
        },
        {
          title: '付款方式',
          dataIndex: 'PAY_TYPE_CODE',
          sorter: true,
          filter: true,
          render: props => {
            return <span>{this.createDictText(props.row.PAY_TYPE_CODE, '8044')}</span>;
          }
        },
        {
          title: '支票号码',
          dataIndex: 'CHECK_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '票据号码',
          dataIndex: 'BILL_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '发票类型',
          dataIndex: 'INVOICE_TYPE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 200
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input',
          showOverflowTooltip: true,
          render: props => {
            return (
              <el-tooltip class="item" content={props.row.REMARK} placement="top">
                <span>{props.row.REMARK}</span>
              </el-tooltip>
            );
          }
        }
      ];
    },
    createTableColumns3() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '车主编号',
          dataIndex: 'OWNER_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车牌号',
          dataIndex: 'LICENSE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'VIN',
          dataIndex: 'VIN',
          sorter: true,
          filter: true,
          filterType: 'input',
          width: 200
        },
        {
          title: '发动机',
          dataIndex: 'ENGINE_NO',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌',
          dataIndex: 'BRAND',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车系',
          dataIndex: 'SERIES',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型',
          dataIndex: 'MODEL',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人',
          dataIndex: 'DELIVERER',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人手机',
          dataIndex: 'DELIVERER_MOBILE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '送修人电话',
          dataIndex: 'DELIVERER_PHONE',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    async getDictList() {
      // 发票类型
      let invoiceList = await findInvoiceType();
      console.log(invoiceList, '发票类型');
      this.formList.find(item => item.fieldName === 'invoiceTypeCode').itemList = invoiceList.data.map(x => ({ text: x.INVOICE_TYPE_NAME, value: x.INVOICE_TYPE_CODE }));
      // employeeName翻译
      this.columns2.find(x => x.dataIndex === 'HANDLER').editItems = (await getAllUser()).data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      this.columns1.find(x => x.dataIndex === 'HANDLER').editItems = (await getAllUser()).data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
    },
    selectCustomer() {
      this.visible = true;
    },
    async getCustomerInfo(val) {
      this.dataSource1 = [];
      this.dataSource2 = [];
      this.dataSource3 = [];
      // this.$refs.formPanel.RESET_FORM();
      this.formList.find(item => item.fieldName === 'preReceiveNo').initialValue = '';
      this.formList.find(item => item.fieldName === 'customerCode').initialValue = '';
      this.formList.find(item => item.fieldName === 'license').initialValue = '';
      this.formList.find(item => item.fieldName === 'customerName').initialValue = '';
      this.formList.find(item => item.fieldName === 'payTypeCode').initialValue = '';
      this.formList.find(item => item.fieldName === 'receiveAmount').initialValue = '';
      this.formList.find(item => item.fieldName === 'checkNo').initialValue = '';
      this.formList.find(item => item.fieldName === 'invoiceTypeCode').initialValue = '';
      this.formList.find(item => item.fieldName === 'billNo').initialValue = '';
      this.formList.find(item => item.fieldName === 'remark').initialValue = '';
      console.log(val, '选择客户');
      this.visible = false;
      // 客户编号
      this.topFilterList.find(item => item.fieldName === 'customerCode').initialValue = val[0].CUSTOMER_CODE;
      this.formList.find(item => item.fieldName === 'customerCode').initialValue = val[0].CUSTOMER_CODE;
      this.formList.find(item => item.fieldName === 'customerCode').disabled = true;
      // 车牌号
      this.formList.find(item => item.fieldName === 'license').initialValue = val[0].LICENSE;
      this.formList.find(item => item.fieldName === 'license').disabled = true;
      // 客户名称
      this.formList.find(item => item.fieldName === 'customerName').initialValue = val[0].CUSTOMER_NAME;
      this.formList.find(item => item.fieldName === 'customerName').disabled = true;
      // 客户类型
      this.formList.find(item => item.fieldName === 'prePayCusType').initialValue = val[0].PRE_PAY_CUS_TYPE;
      // 经手人
      // this.formList.find(item => item.fieldName === 'handler').initialValue  = getUserId();
      // 收款类别
      this.formList.find(item => item.fieldName === 'receiveType').disabled = false;
      this.formList.find(item => item.fieldName === 'payTypeCode').disabled = false;
      this.formList.find(item => item.fieldName === 'receiveAmount').disabled = false;
      this.formList.find(item => item.fieldName === 'checkNo').disabled = false;
      this.formList.find(item => item.fieldName === 'invoiceTypeCode').disabled = false;
      this.formList.find(item => item.fieldName === 'billNo').disabled = false;
      this.formList.find(item => item.fieldName === 'remark').disabled = false;
      console.log(this.fetchParams, '查询');
      this.fetchParams = { customerCode: val[0].CUSTOMER_CODE, xhrAbort: false };
      this.saveFlag = false;
      this.cancelFlag = false;
      // let res1 = await queryPrePay({ customerCode: val[0].CUSTOMER_CODE });
      // if ((res1.resultCode = 200 && res1.data)) {
      //   console.log(res1, '预付款信息');
      //   this.BaseTable1.EXECUTE_INSERT(res1.data.rows);
      // }
      // let res2 = await queryInsurancePay({ customerCode: val[0].CUSTOMER_CODE });
      // if ((res2.resultCode = 200 && res2.data)) {
      //   console.log(res2, '保费信息');
      //   this.BaseTable2.EXECUTE_INSERT(res2.data.rows);
      // }
      // let res3 = await queryVehicle({ customerCode: val[0].CUSTOMER_CODE });
      // if ((res3.resultCode = 200 && res3.data)) {
      //   console.log(res3, '车辆信息');
      //   this.BaseTable3.EXECUTE_INSERT(res3.data.rows);
      // }
    },
    printRecord() {
      this.printVehicledShow = true;
      if (this.formList.find(item => item.fieldName === 'preReceiveNo').initialValue) {
        this.printList = {
          preReceiveNo: this.formList.find(item => item.fieldName === 'preReceiveNo').initialValue,
          customerCode: this.formList.find(item => item.fieldName === 'customerCode').initialValue,
          customerName: this.formList.find(item => item.fieldName === 'customerName').initialValue,
          receiveType: this.createDictText(this.formList.find(item => item.fieldName === 'receiveType').initialValue, '8030'),
          payTypeCode: this.createDictText(this.formList.find(item => item.fieldName === 'payTypeCode').initialValue, '8044'),
          receiveAmount: this.formList.find(item => item.fieldName === 'receiveAmount').initialValue.toFixed(2),
          receiveAmountUp: this.Capitalization(this.formList.find(item => item.fieldName === 'receiveAmount').initialValue.toFixed(2)),
          remark: this.formList.find(item => item.fieldName === 'remark').initialValue
        };
        this.$nextTick(() => {
          this.$refs.printVehicled.EXCUTE_PRINT();
        });
      }
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, val);
    },
    formChange(val) {
      // debugger;
      this.formData = val;
    },
    query() {
      // debugger;
      let customerCode = this.topFilterList.find(item => item.fieldName === 'customerCode').initialValue;
      if (customerCode) {
        this.fetchParams = { customerCode: customerCode, xhrAbort: false };
      }
    },
    clear() {
      // debugger;
      this.topFilterList.find(item => item.fieldName === 'customerCode').initialValue = '';
      this.topFilterList = [...this.topFilterList];
    },
    reset() {
      this.topFilterList.find(item => item.fieldName === 'customerCode').disabled = false;
      this.topFilterList.find(item => item.fieldName === 'customerCode').initialValue = '';
      this.formList.find(item => item.fieldName === 'customerCode').disabled = false;
      this.formList.find(item => item.fieldName === 'license').disabled = false;

      this.formList.find(item => item.fieldName === 'receiveType').disabled = true;
      this.formList.find(item => item.fieldName === 'payTypeCode').disabled = true;
      this.formList.find(item => item.fieldName === 'receiveAmount').disabled = true;
      this.formList.find(item => item.fieldName === 'checkNo').disabled = true;
      this.formList.find(item => item.fieldName === 'invoiceTypeCode').disabled = true;
      this.formList.find(item => item.fieldName === 'billNo').disabled = true;
      this.formList.find(item => item.fieldName === 'remark').disabled = true;

      this.dataSource1 = [];
      this.dataSource2 = [];
      this.dataSource3 = [];
      this.clearFlag = false;
      this.saveFlag = true;
      this.cancelFlag = true;
      // 取消按钮也不可点击
      this.printButtonAble = true;
      this.$refs.formPanel.RESET_FORM();
    },
    async save() {
      this.$refs.formPanel.SUBMIT_FORM();
      console.log(this.formData, 'formPanel');
      if (!this.formData) {
        return;
      }
      let res = await save(this.formData);
      if (res.resultCode == 200) {
        console.log(res, '收款单号');
        this.formList[0].initialValue = res.data.preReceiveNo;
        this.fetchParams = { ...this.fetchParams, xhrAbort: false };
        this.formList.find(item => item.fieldName === 'receiveType').disabled = true;
        this.formList.find(item => item.fieldName === 'payTypeCode').disabled = true;
        this.formList.find(item => item.fieldName === 'receiveAmount').disabled = true;
        this.formList.find(item => item.fieldName === 'checkNo').disabled = true;
        this.formList.find(item => item.fieldName === 'invoiceTypeCode').disabled = true;
        this.formList.find(item => item.fieldName === 'billNo').disabled = true;
        this.formList.find(item => item.fieldName === 'remark').disabled = true;
        this.saveFlag = true;
        this.clearFlag = true;
        this.printButtonAble = false;
        this.topFilterList.find(item => item.fieldName === 'customerCode').disabled = true;
        this.topFilterList = [...this.topFilterList];
        this.$notify.success({ title: '提示信息', message: '保存成功！' });
      } else {
        this.$notify.error({ title: '提示信息', message: '保存失败！' });
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable1.EXECUTE_RESET_HEIGHT();
        this.BaseTable2.EXECUTE_RESET_HEIGHT();
        this.BaseTable3.EXECUTE_RESET_HEIGHT();
      });
    },
    closeHandler(val, type) {
      this.visible = val;
      if (type === 'refresh') {
        // 重新加载
        this.fetchParams = { ...this.fetchParams };
      }
    }
  }
};
</script>

<style lang="less" scoped>
.box {
  border: 1px solid #ccc;
  padding-top: 15px;
  padding-right: 15px;
  border-radius: @borderRadius;
  margin-bottom: 5px;
  box-shadow: @boxShadow;
}
</style>
